package com.szsh.aiot.hsm.service.impl;

import com.szsh.aiot.common.utils.DateUtils;
import com.szsh.aiot.common.utils.StringUtils;
import com.szsh.aiot.hsm.domain.IUserDevice;
import com.szsh.aiot.hsm.domain.homeNetWork.TopoInfo;
import com.szsh.aiot.hsm.enums.FlagType;
import com.szsh.aiot.hsm.enums.NameSource;
import com.szsh.aiot.hsm.mapper.IUserDeviceMapper;
import com.szsh.aiot.hsm.service.UserService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private final IUserDeviceMapper userDeviceMapper;

    public UserServiceImpl(IUserDeviceMapper userDeviceMapper) {
        this.userDeviceMapper = userDeviceMapper;
    }

    @Override
    public IUserDevice getUserDevice(String broadbandNO, TopoInfo topoInfo) {
        // 查询设备是否存在
        IUserDevice userDeviceSearch = new IUserDevice();
        userDeviceSearch.setBroadbandNO(broadbandNO);
        userDeviceSearch.setDeviceMac(topoInfo.getMac());

        List<IUserDevice> userDeviceList = userDeviceMapper.selectIUserDeviceList(userDeviceSearch);
        if (CollectionUtils.isNotEmpty(userDeviceList)) {
            return userDeviceList.get(0);
        }

        // 设备不存在 添加
        String deviceName = StringUtils.isBlank(topoInfo.getDevname()) ? topoInfo.getModel()
                : topoInfo.getDevname();

        IUserDevice userDevice = new IUserDevice();

        userDevice.setBroadbandNO(broadbandNO);
        userDevice.setDeviceMac(topoInfo.getMac());
        userDevice.setDeviceName(deviceName);
        userDevice.setShowName(deviceName);
        userDevice.setNameSource(NameSource.WG.getType());
        userDevice.setIpv4add(topoInfo.getIp());
        userDevice.setIsOnline(topoInfo.getActive());
        userDevice.setIsGateway(FlagType.NO.getVal());
        userDevice.setReceiveTime(DateUtils.getNowDate());

        userDeviceMapper.insertIUserDevice(userDevice);

        return userDevice;
    }
}
